<?php
/**
 * Created by PhpStorm.
 * User: Dean.Wu
 * Date: 2018/2/24 0024
 * Time: 15:18
 */
namespace App\Http\Controllers\Admin;

use App\Models\AdminUsers;
use App\Models\Post;
use App\Models\TagPost;
use App\Models\Tags;
use App\Models\Types;
use App\Models\Users;
use Illuminate\Http\Request;
use zgldh\QiniuStorage\QiniuStorage;

class PostsController extends Controller{

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 文章页面
     * @author Dean.wu
     */
    public function index(){
        $posts=Post::getPostListsData();
        foreach ($posts as $post){
            //分类名称
            $ty_info=Types::getInfoById($post->type_id);
            $post->type_name=$ty_info->name;
            $post->is_admin=$post->is_admin==1?'Admin':'Web';
            //用户名称
            if($post->is_admin==0){
                $user_info=Users::getInfoById($post->user_id);
                $post->user_name=$user_info->name;
            }else{
                $admin_info=AdminUsers::getInfoById($post->user_id);
                $post->user_name=$admin_info->name;
            }

        }
        return view('admin.post.index',compact('posts'));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 创建页面
     */
    public function create(){
        $types = Types::getAllData();
        return view('admin.post.create',compact('types'));
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @name 文章存储
     */
    protected function store()
    {
        $this->validate(request(), [
            'title' => 'required|min:2|unique:posts',
            'type_id' => 'integer',
            'tag' => 'required',
            'content' => 'required|min:15',
        ], [
            'title.required'=>'标题不能为空',
            'unique'=>'该分类已经存在',
            'weight.integer'=>'权重必须是整数！',
            'tag.required'=>'标签不能为空！',
            'content.required'=>'内容不能为空！',
            'content.min'=>'内容不能少于15个字符！',

        ]);

        $title = request('title');
        $type_id = request('type_id');
        $content = request('content');
        $is_admin = 1;
        $user_id = \Auth::guard("admin")->user()->id;
        $post_c=Post::create(compact('title', 'type_id','content','user_id','is_admin'));
        //标签处理
        $tag = request('tag',[]);
        $this->tagHandle($tag,$post_c->id);
        return redirect('/admin/post');
    }

    /**
     * @param $post_id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 文章修改展示
     * @author Deann.wu
     */
    public function edit($post_id){
        //获取文章内容
        $post=Post::getInfoById($post_id);
        //分类信息
        $types = Types::getAllData();
        //标签
        $tagArray=TagPost::getListByUserIdArray($post_id);
        $post->tag_str=implode($tagArray,',');
        return view('admin.post.edit',compact('post','types'));
    }

    /**
     * @param $post_id
     * @return $this|\Illuminate\Http\RedirectResponse
     * @name 数据更新
     * @author Deann.wu
     */
    public function update($post_id){
        $this->validate(request(), [
            'title' => 'required|min:2',
            'type_id' => 'integer',
            'tag' => 'required',
            'content' => 'required|min:15',
        ], [
            'title.required'=>'标题不能为空',
            'weight.integer'=>'权重必须是整数！',
            'tag.required'=>'标签不能为空！',
            'content.required'=>'内容不能为空！',
            'content.min'=>'内容不能少于15个字符！',

        ]);

        $title = request('title');
        $post=Post::getInfoById($post_id);
        //判断是否是同一个标题名称
        if($post->title!=$title){
            $info=Post::where('title',$title)->first();
            if($info){
                return back()->withErrors('标题已经存在了');
            }
        }
        //标签处理

        $type_id = request('type_id');
        $content = request('content');
        $is_admin = $post->is_admin==1?:0;
        $user_id = \Auth::guard("admin")->user()->id;
        Post::where('id',$post_id)->update(compact('title', 'type_id','content','user_id','is_admin'));
        //标签处理
        $tag = request('tag',[]);
        $this->tagHandle($tag,$post_id);
        return back();
    }

    /**
     * @param Request $request
     * @return string
     * @name 上传图片
     * @author Deann.wu
     */
    public function imageUpload(Request $request)
    {
        //TODO::项目整体完成后需要上传到七牛上
        $disk = QiniuStorage::disk('qiniu');
        $time = '/iunan/'.date('YmdHis');
        $filename = $disk->put($time, $request->file('wangEditorH5File'));//上传
        if(!$filename) {
            dd(0);
        }
        $img_url = $disk->downloadUrl($filename); //获取下载链接
        return preg_replace('/\"/', '"', $img_url);
        /*$path = $request->file('wangEditorH5File')->storePublicly(md5(\Auth::id() . time()));
        return asset( 'uploads/'.$path);*/
    }

    /**
     * @param $tags , $post_id
     * @name 标签处理
     * @author Deann.wu
     * @return array
     */
    public function tagHandle($tags,$post_id){
        if(!$post_id){
            return false;
        }
        //处理标签
        $tags=trim(preg_replace("/(\n)|(\s)|(\t)|(\')|(')|(，)/" ,',' ,$tags),',');
        $tags_array=explode(',',$tags);
        //去除数组中重复的值
        $tags_array=array_unique($tags_array);
        //循环判断数组中是否存在该值，有就提取相应的id,没有就存储并并获取id,将tag id 保留下来。
        $tagids=array();//保存id列表
        foreach ($tags_array as $name){
            //获取标签信息
            $tag_info=Tags::getInfoByName($name);
            if(!empty($tag_info)){
                $tagids[]=$tag_info->id;
            }else{
                $c_info=Tags::create(compact('name'));
                $tagids[]=$c_info->id;
            }
        }
        //拥有哪些标签
        $have_tag=TagPost::where('post_id',$post_id)->whereIn('tag_id',$tagids)->pluck('tag_id')->toArray();;
        $have_tag=$have_tag?:[];
        //需要增加
        $add_tags=array_diff($tagids,$have_tag);
        //需要删除
        $del_tags=array_diff($have_tag,$tagids);
        //处理增加逻辑
        if($add_tags){
            foreach ($add_tags as $tag_id){
                TagPost::create(compact('tag_id','post_id'));
            }
        }
        //处理删除逻辑
        if($del_tags){
            foreach ($del_tags as $tag_id){
                TagPost::where([['tag_id','=',$tag_id],['post_id','=',$post_id]])->delete();
            }
        }
        return true;
    }

}